package cn.com.ebidding.dianjian.server.controller;

import cn.com.ebidding.dianjian.server.dao.MongodbDao;
import cn.com.ebidding.dianjian.server.entity.DianJianInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by sehuaqi on 2017/7/6.
 */
@Controller
@RequestMapping(value = "/dianjian")
public class DianJianController {

    @Autowired
    private MongodbDao mongodbDao;

    @RequestMapping(value = "")
    public String console() {

        return "console";
    }

    @RequestMapping(value = "/info")
    @ResponseBody
    public List<DianJianInfo> info() {

        PageRequest pageRequest = new PageRequest(0, 720);

        List<DianJianInfo> dianJianInfos = mongodbDao.findAll();

        return dianJianInfos;
    }

    private PageRequest buildPageRequest(int pageNo, int pageSize, Sort.Direction softType, String sortFiled) {
        Sort sort = null;
        if (StringUtils.isEmpty(softType) || "auto".equals(softType)) {
            sort = new Sort(Sort.Direction.DESC, "id");
        } else {
            sort = new Sort(softType, sortFiled);
        }
        return new PageRequest(pageNo - 1, pageSize, sort);
    }


    @RequestMapping("/infoPage/{pageNo}/{pageSize}")
    @ResponseBody
    public Page<DianJianInfo> infoPage(@PathVariable int pageNo, @PathVariable int pageSize) {

        PageRequest pageRequest = buildPageRequest(pageNo, pageSize, Sort.Direction.DESC, "createTime");

        Page<DianJianInfo> dianJianInfos = mongodbDao.findAll(pageRequest);

        return dianJianInfos;
    }
}
